package com.dure.commonlib.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Environment;
import android.text.TextUtils;
import android.widget.Toast;

import com.dure.commonlib.R;
import com.socks.library.KLog;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileUtils {

    public static String createSDCardDir(String name) {
        File sdcardDir = Environment.getExternalStorageDirectory();
        String path = sdcardDir.getPath() + "/download";
        File file = null;
        try {
            if (Environment.MEDIA_MOUNTED.equals(Environment
                    .getExternalStorageState())) {

                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                file = new File(dir + File.separator + name);
                if (file.exists()) {
                    file.delete();
                }
                file.createNewFile();
            }
        } catch (Exception e) {
            // TODO: handle exception
        }

        return file.getPath();
    }

    public static File fileSelector(Context context) {
        File file = null;

        File rootFiles = Environment.getRootDirectory();

        return file;
    }

    public static void showFileChooser(Activity context) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("file/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            context.startActivityForResult(Intent.createChooser(intent, context.getResources().getString(R.string.chose_open_tile)),
                    1);
        } catch (android.content.ActivityNotFoundException ex) {
            // Potentially direct the user to the Market with a Dialog
            Toast.makeText(context, context.getResources().getString(R.string.please_install_file_manager), Toast.LENGTH_SHORT)
                    .show();
        }
    }

    public static InputStream getInputStream(FileInputStream fileInput) {
        byte[] byteArray = streamToByteArray(fileInput);
        return byteArrayToStream(byteArray);
    }

    public static byte[] streamToByteArray(InputStream inputStream) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n;

        try {
            while ((n = inputStream.read(buffer)) != -1) {
                baos.write(buffer, 0, n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        byte[] byteArray = baos.toByteArray();
        try {
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return byteArray;
    }

    public static InputStream byteArrayToStream(byte[] byteArray) {
        return new ByteArrayInputStream(byteArray);
    }

    public static void deleteFiles(String filePath) {
        if (!TextUtils.isEmpty(filePath)) {
            File file = new File(filePath);
            if (file != null && file.isDirectory()) {
                if (file.listFiles() != null && file.listFiles().length != 0) {
                    for (File childFile : file.listFiles()) {
                        if (childFile.isFile()) {
                            childFile.delete();
                        }
                    }
                }
            }

        }
    }

    /**
     * 创建文件
     * @param destFileName
     * @return
     */
    public static boolean createFile(String destFileName) {
        File file = new File(destFileName);
        if (file.exists()) {
            System.out.println("创建单个文件" + destFileName + "失败，目标文件已存在！");
            file.delete();
        }
        if (destFileName.endsWith(File.separator)) {
            System.out.println("创建单个文件" + destFileName + "失败，目标不能是目录！");
            return false;
        }
        if (!file.getParentFile().exists()) {
            System.out.println("目标文件所在路径不存在，准备创建。。。");
            if (!file.getParentFile().mkdirs()) {
                System.out.println("创建目录文件所在的目录失败！");
                return false;
            }
        }

        // 创建目标文件
        try {
            if (file.createNewFile()) {
                System.out.println("创建单个文件" + destFileName + "成功！");
                return true;
            } else {
                System.out.println("创建单个文件" + destFileName + "失败！");
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("创建单个文件" + destFileName + "失败！");
            return false;
        }
    }

    /**
     * 得到一个可用的缓存目录(如果外部可用使用外部,否则内部)。
     *
     * @param context
     *            上下文信息
     * @param uniqueName
     *            目录名字
     * @return 返回目录名字
     */
    public static String getDiskCacheDirForPath(Context context,
                                                String uniqueName) {
        // 检查是否安装或存储媒体是内置的,如果是这样,试着使用
        // 外部缓存 目录
        // 否则使用内部缓存 目录
        final String cachePath = Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState()) ? getExternalCacheDir(context)
                .getPath() : context.getCacheDir().getPath();
        if(uniqueName == null){
            return (cachePath);
        }else{
            return (cachePath + File.separator + uniqueName + "/");
        }

    }

    /**
     * 获得外部应用程序缓存目录
     *
     * @param context
     *            上下文信息
     * @return 外部缓存目录
     */
    public static File getExternalCacheDir(Context context) {
        final String cacheDir = "/Android/data/" + context.getPackageName()
                + "/cache/";

        return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
    }

    /**
     * 将bitmap写入到指定的文件中
     *
     * @param bitmap
     * @param filePath
     */
    public static void bitmapWriteToCacheDir(Bitmap bitmap, String filePath) {
        if (filePath == null) {
            return;
        }

        FileOutputStream iStream = null;
        try {
            if(createFile(filePath)){
                iStream = new FileOutputStream(new File(filePath));
                int index = filePath.lastIndexOf(".");
                if (index != -1) {
                    String fileType = filePath.substring(index + 1);
                    KLog.d("lesleixz", "fileType = " + fileType);
                    if (TextUtils.equals(fileType,"jpg")||TextUtils.equals(fileType, "jpeg")) {
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, iStream);
                    }else if (TextUtils.equals(fileType,"png")){
                        bitmap.compress(Bitmap.CompressFormat.PNG, 50, iStream);
                    }
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if(iStream !=null){
                    iStream.flush();
                    iStream.close();
                }

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            iStream = null;
        }
    }

}
